#include "StdAfx.h"
#include "Log.h"
#include "SessionSocket.h"

CLog::CLog(void)
{
	m_pLock = new CSafeLock;
	m_pRegistLock = new CSafeLock;
	m_strLog = "";
	m_hWnd = NULL;
}

CLog::~CLog(void)
{
	if(m_pLock)
	{
		delete m_pLock;
		m_pLock = NULL;
	}

	SAFE_DELETE(m_pRegistLock);
	m_MapInfo.clear();
}

void CLog::SetWindow(HWND hWnd)
{
	m_hWnd = hWnd;
}


void CLog::ReadLog(CString& strLog)
{
	m_pLock->Lock();

	strLog = m_strLog;

	m_pLock->UnLock();
}

void CLog::ShowLog()
{
	if(IsWindow(m_hWnd))
	{
		m_pLock->Lock();

		CWnd* pWnd = CWnd::FromHandle(m_hWnd);
		pWnd->SetWindowText(m_strLog);
		int nPos = pWnd->GetWindowTextLength();
		((CEdit*)pWnd)->SetSel(nPos,nPos);

		m_pLock->UnLock();
	}
}


void CLog::RegisterSessionLink(CString strSrcIP, CString strDstIP)
{
	m_pRegistLock->Lock();
	m_MapInfo[strSrcIP]++;

	SYSTEMTIME systime;
	GetLocalTime(&systime);
	CString strTime;
	strTime.Format("%d:%d:%d",systime.wHour,systime.wMinute,systime.wSecond);
	AppendLog("%s  %s connect to %s",strTime.GetBuffer(),strSrcIP.GetBuffer(),strDstIP.GetBuffer());

	m_pRegistLock->UnLock();
}

void CLog::UnRegisterSessionLink(CString strSrcIP, CString strDstIP)
{
	m_pRegistLock->Lock();

	if(m_MapInfo[strSrcIP] > 0)
	{
		m_MapInfo[strSrcIP]--;

		SYSTEMTIME systime;
		GetLocalTime(&systime);
		CString strTime;
		strTime.Format("%d:%d:%d",systime.wHour,systime.wMinute,systime.wSecond);
		
		AppendLog("%s  %s disconnect to %s",strTime.GetBuffer(),strSrcIP.GetBuffer(),strDstIP.GetBuffer());
		if(m_MapInfo[strSrcIP] == 0)
		{
			AppendLog("%s  %s id disconnection!",strTime.GetBuffer(),strSrcIP.GetBuffer());
		}
	}

	m_pRegistLock->UnLock();
}



#ifdef _DEBUG 
#if _UNICODE 
void CLog::AppendLog(LPCWSTR str,...) 
{ 
	m_pLock->Lock();

	va_list args; 
	va_start(args,str); 
	int len = _vscwprintf((const wchar_t *)str,args) + 1; 
	wchar_t *lpszStr = new wchar_t[len]; 
	if (lpszStr == NULL) 
	{ 
		throw _T("Alloc memory error"); 
	} 
	vswprintf((wchar_t *)lpszStr,(const wchar_t *)str,args); 
	va_end(args); 

	m_strLog += lpszStr;
	m_strLog += "\r\n";

	delete[] lpszStr; 

	m_pLock->UnLock();

	ShowLog();
} 
#else 
void CLog::AppendLog(LPCTSTR str,...) 
{ 
	m_pLock->Lock();

	va_list args; 
	va_start(args,str); 
	int len = _vscprintf((const char *)str,args) + 1; 
	char *lpszStr = new char[len]; 
	if (lpszStr == NULL) 
	{ 
		throw _T("Alloc memory error"); 
	} 
	vsprintf((char *)lpszStr,(const char *)str,args); 
	va_end(args); 

	m_strLog += lpszStr;
	m_strLog += "\r\n";

	delete[] lpszStr; 

	m_pLock->UnLock();

	ShowLog();
} 
#endif 
#else 
#define WTrace NULL 
#endif